import modelAbstract from "./modelAbstract";
import { images } from "../service/image";
import play from "../canvas/play";
import untils from "../untils";
// 导入库
import _ from 'lodash';
import { directionEnum } from "../enum/directionEnum";
import bullet from "../canvas/bullet";
// 草地模型子类
export default class playModel extends modelAbstract implements IModel {
  public ctx: ICanvas = play;
  name: string = 'play';
  bindEvent = false;
  render(): void {
    super.draw();
    if (!this.bindEvent) {
      this.bindEvent = true;
       // 切换玩家方向
      document.addEventListener('keydown', this.changeDirection.bind(this));
      // 玩家移动
      document.addEventListener('keydown', this.move.bind(this));
      // 玩家发射子弹
      document.addEventListener('keydown', (event: KeyboardEvent) => {
        if (event.code === 'Space') bullet.addPlayBullet();
      });
    };
  };
  image() {
    let direction = this.name + _.upperFirst(this.direction);
    return <HTMLImageElement>images.get(direction as any);
  };
  changeDirection(e: KeyboardEvent) {
    // console.log('keyEvent:', e);
    switch (e.code) {
      case 'ArrowUp':
        this.direction = directionEnum.top;
        break;
      case 'ArrowDown':
        this.direction = directionEnum.bottom;
        break;
      case 'ArrowLeft':
        this.direction = directionEnum.left;
      break;
      case 'ArrowRight':
        this.direction = directionEnum.right;
        break;
    };
    this.ctx.renderModel();
  };
  move(e: KeyboardEvent) {
    let x = this.posX;
    let y = this.posY;
    switch (e.code) {
      case 'ArrowUp':
        y -= 5;
        break;
      case 'ArrowDown':
        y += 5;
        break;
      case 'ArrowLeft':
        x -= 5;
        break;
      case 'ArrowRight':
        x += 5;
        break;
    };
    if (untils.isModelTouch(x, y) || untils.isCanvasTouch(x, y)) {
      return;
    };
    this.posX = x;
    this.posY = y;
    this.ctx.renderModel();
  }
};